package com.zjcloud.jwgl.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjcloud.common.annotation.Anonymous;
import com.zjcloud.common.annotation.Log;
import com.zjcloud.common.core.controller.BaseController;
import com.zjcloud.common.core.domain.AjaxResult;
import com.zjcloud.common.enums.BusinessType;
import com.zjcloud.jwgl.domain.AcScheduleConstraint;
import com.zjcloud.jwgl.domain.AcScheduleConstraintTemplate;
import com.zjcloud.jwgl.domain.AcConstraintType;
import com.zjcloud.jwgl.service.IAcScheduleConstraintService;
import com.zjcloud.jwgl.service.IAcScheduleConstraintTemplateService;
import com.zjcloud.jwgl.service.IAcConstraintTypeService;
import com.zjcloud.common.utils.poi.ExcelUtil;
import com.zjcloud.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 排课约束条件Controller
 * 
 * @author wxl
 * @date 2024-09-13
 */
@RestController
@RequestMapping("/jwgl/constraint")
public class AcScheduleConstraintController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(AcScheduleConstraintController.class);
    
    @Autowired
    private IAcScheduleConstraintService acScheduleConstraintService;
    
    @Autowired
    private IAcScheduleConstraintTemplateService acScheduleConstraintTemplateService;
    
    @Autowired
    private IAcConstraintTypeService acConstraintTypeService;

    /**
     * 查询排课约束条件列表
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:list')")
    @GetMapping("/list")
    public TableDataInfo list(AcScheduleConstraint acScheduleConstraint) {
        startPage();
        List<AcScheduleConstraint> list = acScheduleConstraintService.selectAcScheduleConstraintList(acScheduleConstraint);
        return getDataTable(list);
    }

    /**
     * 导出排课约束条件列表
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:export')")
    @Log(title = "排课约束条件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AcScheduleConstraint acScheduleConstraint) {
        List<AcScheduleConstraint> list = acScheduleConstraintService.selectAcScheduleConstraintList(acScheduleConstraint);
        ExcelUtil<AcScheduleConstraint> util = new ExcelUtil<AcScheduleConstraint>(AcScheduleConstraint.class);
        util.exportExcel(response, list, "排课约束条件数据");
    }

    /**
     * 获取排课约束条件详细信息
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(acScheduleConstraintService.selectAcScheduleConstraintById(id));
    }

    /**
     * 新增排课约束条件
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:add')")
    @Log(title = "排课约束条件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AcScheduleConstraint acScheduleConstraint) {
        return toAjax(acScheduleConstraintService.insertAcScheduleConstraint(acScheduleConstraint));
    }

    /**
     * 修改排课约束条件
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:edit')")
    @Log(title = "排课约束条件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AcScheduleConstraint acScheduleConstraint) {
        return toAjax(acScheduleConstraintService.updateAcScheduleConstraint(acScheduleConstraint));
    }

    /**
     * 删除排课约束条件
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:remove')")
    @Log(title = "排课约束条件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(acScheduleConstraintService.deleteAcScheduleConstraintByIds(ids));
    }

    /**
     * 批量更新约束权重
     */
    @Log(title = "排课约束条件", businessType = BusinessType.UPDATE)
    @PutMapping("/weights")
    public AjaxResult updateWeights(@RequestBody List<AcScheduleConstraint> constraints) {
        try {
            // 参数校验
            if (constraints == null || constraints.isEmpty()) {
                return error("约束条件数据不能为空");
            }
            
            // 校验每个约束条件的必要字段并处理type到constraintTypeId的转换
            for (AcScheduleConstraint constraint : constraints) {
                // 如果constraintTypeId为空但type不为空，尝试根据type查找constraintTypeId
                if (constraint.getConstraintTypeId() == null && constraint.getType() != null) {
                    AcConstraintType constraintType = acConstraintTypeService.selectAcConstraintTypeByCode(constraint.getType());
                    if (constraintType != null) {
                        constraint.setConstraintTypeId(constraintType.getId());
                    }
                }
                
                if (constraint.getConstraintTypeId() == null || 
                    constraint.getWeight() == null || 
                    constraint.getSemester() == null) {
                    return error("约束条件数据不完整，请检查约束类型、权重和学期信息");
                }
            }
            
            // 批量更新或创建约束权重
            int rows = acScheduleConstraintService.saveOrUpdateConstraintWeights(constraints);
            return toAjax(rows);
        } catch (Exception e) {
            logger.error("更新约束权重失败", e);
            return error("更新约束权重失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取指定学期的启用约束条件
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:list')")
    @GetMapping("/enabled/{semester}")
    public AjaxResult getEnabledConstraints(@PathVariable("semester") String semester) {
        return success(acScheduleConstraintService.getEnabledConstraints(semester));
    }

    /**
     * 从模板初始化约束条件
     */
    @PreAuthorize("@ss.hasPermi('jwgl:constraint:edit')")
    @PostMapping("/initFromTemplate")
    public AjaxResult initFromTemplate(@RequestParam("templateName") String templateName, @RequestParam("semester") String semester) {
        try {
            int result = acScheduleConstraintService.initConstraintsFromTemplate(templateName, semester);
            if (result > 0) {
                return AjaxResult.success("从模板初始化成功，共创建" + result + "条约束条件");
            } else {
                return AjaxResult.error("初始化失败，模板不存在或无数据");
            }
        } catch (Exception e) {
            log.error("从模板初始化约束条件失败", e);
            return AjaxResult.error("初始化失败：" + e.getMessage());
        }
    }

    /**
     * 应用默认模板
     */
    @PreAuthorize("@ss.hasPermi('jwgl:constraint:edit')")
    @PostMapping("/applyDefaultTemplate")
    public AjaxResult applyDefaultTemplate(@RequestParam("semester") String semester) {
        try {
            int result = acScheduleConstraintService.applyDefaultTemplate(semester);
            if (result > 0) {
                return AjaxResult.success("应用默认模板成功，共创建" + result + "条约束条件");
            } else {
                return AjaxResult.error("应用失败，默认模板不存在或无数据");
            }
        } catch (Exception e) {
            log.error("应用默认模板失败", e);
            return AjaxResult.error("应用失败：" + e.getMessage());
        }
    }

    /**
     * 获取可用模板列表
     */
    // @PreAuthorize("@ss.hasPermi('jwgl:constraint:list')")
    @Anonymous
    @GetMapping("/templates")
    public TableDataInfo getTemplates(AcScheduleConstraintTemplate acScheduleConstraintTemplate) {
        startPage();
        List<AcScheduleConstraintTemplate> list = acScheduleConstraintTemplateService.selectAcScheduleConstraintTemplateList(acScheduleConstraintTemplate);
        return getDataTable(list);
    }
    

}